package com.piece.file.preview;

import com.piece.core.framework.util.file.FileUtil;
import com.piece.file.support.FileAttribute;
import com.piece.file.client.FileClientFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;

/**
 * 处理pdf文件
 */
@Slf4j
@Service
public class PdfFilePreview implements FilePreviewHandle {

    @Resource
    protected FileClientFactory fileClientFactory;

    @Value("${file.converted.charset:utf-8}")
    public String charset;

    @Override
    public String handle(FileAttribute fileAttribute, HttpServletRequest request, Model model, boolean edit) {
        String fileName = fileAttribute.getName();
        String suffix = FileUtil.getFileSuffix(fileName);

        try {
            model.addAttribute("name", fileName);
            model.addAttribute("url", URLDecoder.decode(fileAttribute.getUrl(), charset));
            return "/file/pdf";
        } catch (Exception e) {
            model.addAttribute("fileType", suffix);
            model.addAttribute("msg", e.getMessage());
            return "/file/fileNotSupported";
        }
    }
}
